package com.prb.tomcat.handler;

import com.prb.tomcat.protocol.ResponseRequestHolder;
import com.prb.tomcat.utils.FileUtil;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import static com.prb.tomcat.protocol.StatusEnum.*;

public class ErrorHandler {


    private static final String INDEX_PAGE = "index.html";

    //处理 404
    public static void handleNotFound(SocketChannel channel)  {
        try {
            handleError(channel, NOT_FOUND.getCode());
        } catch (Exception e) {
            handleInternalServerError(channel);
        }
    }

    //处理 400 error
    public static void handleBadRequest(SocketChannel channel) {
        try {
            handleError(channel, BAD_REQUEST.getCode());
        } catch (Exception e) {
            handleInternalServerError(channel);
        }
    }

    //处理 403 资源被禁止
    public static void handleForbidden(SocketChannel channel) {
        try {
            handleError(channel, FORBIDDEN.getCode());
        } catch (Exception e) {
            handleInternalServerError(channel);
        }
    }

    //处理 500 error
    public static void handleInternalServerError(SocketChannel channel) {
        try {
            handleError(channel, INTERNAL_SERVER_ERROR.getCode());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //处理错误 ， 返回错误页面
    public static void handleError(SocketChannel channel, int statusCode) throws IOException {
        ResponseRequestHolder headers = new ResponseRequestHolder(statusCode);

        ByteBuffer bodyBuffer = FileUtil.readFile(String.format("/%d.html", statusCode));
        headers.setContentLength(bodyBuffer.capacity());
        headers.setContentType("text/html");
        ByteBuffer headerBuffer = ByteBuffer.wrap(headers.toString().getBytes());

        channel.write(new ByteBuffer[]{headerBuffer, bodyBuffer});
    }



}
